package com.gulimall.cart.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gulimall.cart.vo.Member;
import com.gulimall.cart.vo.UserKeyInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Component
public class CookieInterceptor implements HandlerInterceptor {

    /**
     * 30天过期时间user-key cookie
     */
    public static final int USER_KEY_TIMEOUT = 60 * 60 * 24 * 30;

    public static final ThreadLocal<UserKeyInfo> userKeyInfoThreadLocal = new ThreadLocal<>();

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserKeyInfo userKeyInfo= new UserKeyInfo();
        userKeyInfoThreadLocal.set(userKeyInfo);

        HttpSession session = request.getSession(false);
        // 用户已登录状态
        if (session != null) {
            Object userObj = session.getAttribute("user");
            if (userObj != null) {
                JSONObject userJson = (JSONObject) userObj;
                Member user = userJson.toJavaObject(Member.class);
                userKeyInfo.setUserId(user.getId());
            }
        }
        Cookie[] cookies = request.getCookies();
        // 遍历查看是否有user-key，没有就下发
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("user-key".equals(cookie.getName())) {
                    // 利用threadLocal放入user-key
                    userKeyInfo.setUserKey(cookie.getValue());
                }
            }
        }
        if (userKeyInfo.getUserKey() == null){
            // 用户未登录状态
            userKeyInfo.setUserKey(UUID.randomUUID().toString());
            userKeyInfo.setNewUserKey(true);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserKeyInfo userKeyInfo = userKeyInfoThreadLocal.get();

        // 是新key就下发
        if (userKeyInfo.isNewUserKey()) {
            Cookie cookie = new Cookie("user-key", userKeyInfo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(USER_KEY_TIMEOUT);
            response.addCookie(cookie);
        }

    }

}
